using SqlSugar;
using TestWebApi.IServices;
using TestWebApi.Models;
using TestWebApi.Util;

namespace TestWebApi.Services;

public class UserService(JwtHelper jwtHelper, DatabaseContext dbContext) : IUserService
{
    /// <summary>
    ///注册用户
    /// </summary>
    public string? GetUserToken<T>(T user) where T : LoginModel
    {
        var token = jwtHelper.GenerateToken(user);
        return token ?? null;
    }

    /// <summary>
    /// 检查用户是否存在
    /// </summary>
    /// <param name="email"></param>
    /// <param name="connectionName"></param>
    /// <returns></returns>
    public bool UserExists(string email, string connectionName)
    {
        try
        {
            //根据连接名称（DefaultConnection）获取指定数据库连接的实例
            var dbclient = dbContext.GetDbContext(connectionName);
            var IsUserTable = dbclient.DbMaintenance.IsAnyTable("User");
            if (!IsUserTable) //用来判断User表是否存在
            {
                // 创建表
                CreateUsersTable((SqlSugarClient)dbclient);
                //AppLogger.Information("用户表不存在，已创建用户表");
                return false;
            }

            // 查询是否存在具有相同电子邮件的用户
            var count = dbclient.Queryable<UserModel>().Where(u => u.Email == email).Count();
            return count > 0;
        }
        catch (Exception ex)
        {
            //AppLogger.Error(ex, "检查用户是否存在时发生错误: {Message}", ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="userModel">用户实体类</param>
    /// <param name="connectionName">数据库连接名称</param>
    public bool CreateUser(UserModel userModel, string connectionName)
    {
        try
        {
            if (UserExists(userModel.Email, connectionName))
            {
             //   AppLogger.Information("该邮箱已注册，无法创建");
                return false;
            }
            //根据连接名称（DefaultConnection）获取指定数据库连接的实例‘
            var dbclient = dbContext.GetDbContext(connectionName);
            //向User表插入user数据
            dbclient.Insertable(userModel).ExecuteCommand();
            return UserExists(userModel.Email, connectionName);
        }
        catch (Exception ex)
        {
         //   AppLogger.Error(ex, "创建用户时发生错误: {Message}", ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 验证用户密码
    /// </summary>
    /// <param name="email">邮箱</param>
    /// <param name="password">密码</param>
    /// <param name="connectionName">连接名称</param>
    /// <returns></returns>
    public bool CheckUserPassword(string email, string password, string connectionName)
    {
        try
        {
            var dbclient = dbContext.GetDbContext(connectionName);
            var user = dbclient.Queryable<UserModel>().Where(u => u.Email == email).First();
            return user != null && user.Pwd == password;
        }
        catch (Exception ex)
        {
           // AppLogger.Error(ex, "检查用户密码时发生错误: {Message}", ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 创建用户表
    /// </summary>
    /// <param name="dbclient"></param>
    private void CreateUsersTable(SqlSugarClient dbclient)
    {
        var columns = new List<DbColumnInfo>
        {
            new DbColumnInfo
            {
                DbColumnName = "Id", IsPrimarykey = true, IsIdentity = true, IsNullable = false,
                PropertyType = typeof(int), DataType = "int"
            },
            new DbColumnInfo
            {
                DbColumnName = "UserName", PropertyType = typeof(string), DataType = "varchar(15)", IsNullable = false
            },
            new DbColumnInfo
            {
                DbColumnName = "Role", PropertyType = typeof(int), DataType = "int", IsNullable = false,
                DefaultValue = "1"
            },
            new DbColumnInfo
            {
                DbColumnName = "Email", PropertyType = typeof(string), DataType = "varchar(255)", IsNullable = false
            },
            new DbColumnInfo
                { DbColumnName = "Pwd", PropertyType = typeof(string), DataType = "varchar(255)", IsNullable = false },
            new DbColumnInfo
            {
                DbColumnName = "Age", PropertyType = typeof(int), DataType = "int", IsNullable = true,
                DefaultValue = "0"
            },
            new DbColumnInfo
            {
                DbColumnName = "Sex", PropertyType = typeof(string), DataType = "varchar(255)", IsNullable = true,
                DefaultValue = "男"
            }
        };

        dbclient.DbMaintenance.CreateTable("User", columns, true);
    }
}